package com.abase.site.client.widget.header;

import com.abase.site.client.PocAbase;

import com.abase.site.client.PocAbaseHistoryHandler.HistoryTokens;
import com.abase.site.client.events.LoginRequestEvent;
import com.abase.site.client.events.LoginResponseEvent;
import com.abase.site.client.events.LoginResponseHandler;
import com.abase.site.client.prive.widget.login.AbaseLoginManager;
import com.abase.site.shared.AbaseProfile;
import com.abase.site.shared.login.LoginResponse;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class AbaseHeader extends Composite implements LoginResponseHandler {

	private static AbaseHeaderUiBinder uiBinder = GWT
			.create(AbaseHeaderUiBinder.class);

	interface AbaseHeaderUiBinder extends UiBinder<Widget, AbaseHeader>  {
	}
	
	private Boolean isIntranetMode = false;
	
	@UiField FlowPanel privateBandeau;
	@UiField HorizontalPanel openMenu;
	
	@UiField Label linkHomeLabel;
	@UiField Label linkTestLabel;
	@UiField Label email;
	@UiField Button loginLink;

	private AbaseProfile profile = null;

	public AbaseHeader() {
		initWidget(uiBinder.createAndBindUi(this));
		PocAbase.getEventBus().addHandler(LoginResponseEvent.TYPE, this);
		redraw();
	}
	
	private void redraw() {
		if (this.isIntranetMode && null != this.profile) {
			this.loginLink.setText(AbaseHeaderMessages.INSTANCE.getLogout());
			this.openMenu.setVisible(false);
			this.privateBandeau.setVisible(true);
			this.email.setText(this.profile.getEmail());
		} else {
			this.loginLink.setText(AbaseHeaderMessages.INSTANCE.getLogin());
			this.openMenu.setVisible(true);
		}
		
	}


	@UiHandler({"linkHomeLabel","linkTestLabel","loginLink" })
	void onClick(ClickEvent e) {
		if (e.getSource() == this.linkHomeLabel) {
		  History.newItem(HistoryTokens.HOME_TOKEN.getValue());
		} else if (e.getSource() == this.linkTestLabel) {
		  History.newItem(HistoryTokens.HISTORY_TEST_TOKEN.getValue());
		} else if (e.getSource() == this.loginLink) {
			PocAbase.getEventBus().fireEvent(new LoginRequestEvent());
		}
	}

	@Override
	public void onLoginResponse(LoginResponseEvent event) {
		if (null != event.getContext().getProfile()) {
			this.isIntranetMode = true;
			this.profile = (AbaseProfile)event.getContext().getProfile();
			redraw();
		}
		
	}

}
